<template>
  <view>

    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-button">
        <uni-icons
            type="left"
            size="24"
            @click="goBack()"
            style="margin-right: 20rpx"
        ></uni-icons>
      </view>
      <view class="nav-title">订单支付</view>
      <view class="nav-right">
        <uni-icons type="ellipsis" size="28" color="#000"></uni-icons>
      </view>
    </view>

    <view class="amount">
      <text>￥</text>
      {{ dataInfo.price }}
    </view>
    <view class="pay-tips">支付金额</view>
    <view class="pay-info-item">
      <view class="film-title">{{ dataInfo.movieName }}</view>
      <view class="film-text">{{ dataInfo.cinemaName }}</view>
      <view class="film-text">{{ dataInfo.cinemaAddress }}</view>
    </view>
    <s-payment-method
        :state="state"
        @onTapPay="onTapPay"
        :showMixed="false"
    ></s-payment-method>
    
    <view class="pay-btns" @click="paySubmit">确认支付</view>
  </view>

</template>

<script setup>
import {ref} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import sheep from "@/sheep";

// 响应式数据声明
const state = ref({
  payMethods: ["wechat", "money"], // 只保留微信支付和余额支付
  payment: "" // 当前选中的支付方式
});

let dataInfo = ref({
  price: 0,
  movieName: '',
  cinemaName: '',
  cinemaAddr: '',
  showInfo: {}
});

const payMethod = ref(""); // 支付方式代码：1-微信 2-余额
const orderId = ref("");

// 生命周期钩子
onLoad(async (opt) => {
  if (!opt.orderId) {
    uni.showToast({icon: 'error', title: '订单号不存在'});
    return;
  }
  orderId.value = opt.orderId;
  try {
    await getOrderInfo(opt.orderId);
  } catch (error) {
    console.error('页面初始化失败:', error);
    uni.showToast({icon: 'error', title: '数据加载失败'});
  }
  console.log('userInfo: ', uni.getStorageSync('user-store').userInfo);
});

// 支付方式选择
const onTapPay = (e) => {
  console.log('========== 选择支付方式 ==========');
  console.log('收到的支付方式标识:', e);
  
  // 更新选中状态（用于组件显示）
  state.value.payment = e;
  
  // 映射到后端支付类型代码
  switch (e) {
    case "wechat":
      payMethod.value = 1; // 微信支付 (对应后端 wechatType = 1)
      console.log('✅ 已选择：微信支付');
      break;
    case "money":
      payMethod.value = 2; // 余额支付 (对应后端 wechatType = 2)
      console.log('✅ 已选择：余额支付');
      break;
    default:
      payMethod.value = "";
      console.log('⚠️ 未知的支付方式');
  }
  
  console.log('state.payment:', state.value.payment);
  console.log('payMethod.value:', payMethod.value);
  console.log('==================================');
};


// 获取订单信息
const getOrderInfo = async (orderId) => {
  try {
    const res = await sheep.$api.xkMovie.orderDetail({
      orderId: orderId
    });

    const backParams = JSON.parse(res.data.backParams);
    const movieInfo = JSON.parse(res.data.movieInfo);
    dataInfo.value.price = res.data.orderPrice;
    dataInfo.value.movieName = movieInfo?.movieName || backParams?.filmName;
    dataInfo.value.cinemaName = backParams.cinemaName;
    dataInfo.value.cinemaAddress = backParams?.cinemaAddr || backParams?.cinemaAddress;
  } catch (error) {
    console.error('获取订单信息失败:', error);
    uni.showToast({icon: 'error', title: '获取订单失败'});
  }
};

// 支付提交处理
const paySubmit = () => {
  console.log('========== 点击确认支付 ==========');
  console.log('当前 payMethod.value:', payMethod.value);
  console.log('当前 state.payment:', state.value.payment);
  
  if (!payMethod.value) {
    console.log('❌ 支付方式未选择');
    uni.showToast({
      icon: 'none', 
      title: '请选择支付方式',
      duration: 2000
    });
    return;
  }

  // 根据支付方式调用对应方法
  const payMethods = {
    1: miniPay,      // 微信支付 (wechatType = 1)
    2: balancePay    // 余额支付 (wechatType = 2)
  };

  const payFunction = payMethods[payMethod.value];
  if (payFunction) {
    console.log('✅ 执行支付方法，支付类型:', payMethod.value);
    payFunction();
  } else {
    console.error('❌ 未找到对应的支付方法，支付类型:', payMethod.value);
    uni.showToast({icon: 'error', title: '支付方式错误'});
  }
  console.log('==================================');
};

// 余额支付
const balancePay = async () => {
  try {
    console.log('========== 开始余额支付 ==========');
    
    // 获取用户信息，检查余额
    const userInfo = sheep.$store("user").userInfo;
    console.log('当前用户信息:', userInfo);
    console.log('用户余额:', userInfo.price);
    console.log('订单金额:', dataInfo.value.price);
    
    const userBalance = parseFloat(userInfo.price) || 0;
    const orderAmount = parseFloat(dataInfo.value.price) || 0;
    
    // 检查余额是否充足
    if (userBalance < orderAmount) {
      console.log('❌ 余额不足');
      uni.showModal({
        title: '余额不足',
        content: `您的余额为 ${userBalance.toFixed(2)} 元，订单金额为 ${orderAmount.toFixed(2)} 元，余额不足，请选择微信支付`,
        showCancel: false
      });
      return;
    }
    
    console.log('✅ 余额充足，弹出二次确认框');
    
    // 二次确认支付
    uni.showModal({
      title: '确认支付',
      content: `确认使用余额支付 ${orderAmount.toFixed(2)} 元？\n\n支付后余额：${(userBalance - orderAmount).toFixed(2)} 元`,
      confirmText: '确认支付',
      cancelText: '取消',
      success: async (confirmRes) => {
        if (confirmRes.confirm) {
          console.log('✅ 用户确认支付，开始调用接口');
          uni.showLoading({title: '支付中...'});
          
          try {
            const res = await sheep.$api.xkMovie.payMovieAdd({
              payId: orderId.value,
              wechatType: 2, // 余额支付
            });
            
            uni.hideLoading();
            console.log('余额支付接口返回:', res);
            
            if (res.code === 200) {
              console.log('✅ 支付成功');
              // 更新用户信息
              await sheep.$store("user").getInfo();
              uni.showToast({icon: 'success', title: '支付成功'});
              setTimeout(() => {
                uni.navigateTo({url: '/pages/xk-movie/my-ticket'});
              }, 1500);
            } else {
              console.log('❌ 支付失败:', res.msg);
              uni.showToast({
                icon: 'none', 
                title: res.msg || '支付失败，请重试',
                duration: 3000
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error('❌ 余额支付异常:', error);
            uni.showToast({
              icon: 'error', 
              title: error.message || '支付失败，请重试',
              duration: 3000
            });
          }
        } else {
          console.log('⚠️ 用户取消支付');
        }
      }
    });
    
    console.log('==================================');
  } catch (error) {
    console.error('❌ 余额支付流程异常:', error);
    uni.showToast({icon: 'error', title: '支付失败，请重试'});
  }
};

// 微信支付
const miniPay = async () => {
  try {
    const res = await sheep.$api.xkMovie.payMovieAdd({
      payId: orderId.value,
      wechatType: 1,
    });
    
    console.log('微信支付接口返回:', res);
    console.log('完整返回数据:', JSON.stringify(res));
    
    if (res.code === 200) {
      // 打印所有字段，便于调试
      console.log('支付数据字段检查:', {
        hasData: !!res.data,
        timeStamp: res.data?.timeStamp,
        timestamp: res.data?.timestamp,
        nonceStr: res.data?.nonceStr,
        noncestr: res.data?.noncestr,
        package_: res.data?.package_,
        package: res.data?.package,
        prepayId: res.data?.prepayId,
        prepay_id: res.data?.prepay_id,
        signType: res.data?.signType,
        paySign: res.data?.paySign,
        sign: res.data?.sign,
      });
      
      // 兼容不同的字段名
      const payData = {
        timeStamp: res.data?.timeStamp || res.data?.timestamp || String(Date.now()),
        nonceStr: res.data?.nonceStr || res.data?.noncestr || '',
        package: res.data?.package || res.data?.package_ || '',
        signType: res.data?.signType || 'RSA',
        paySign: res.data?.paySign || res.data?.sign || '',
      };
      
      console.log('处理后的支付参数:', payData);
      console.log('package值:', payData.package);
      
      // 检查必需参数
      if (!payData.nonceStr || !payData.package || !payData.paySign) {
        console.error('支付参数不完整，缺少必需字段');
        console.error('缺少的参数:', {
          nonceStr: !payData.nonceStr ? '缺失' : '存在',
          package: !payData.package ? '缺失' : '存在',
          paySign: !payData.paySign ? '缺失' : '存在',
        });
        uni.showToast({
          icon: 'none', 
          title: '支付参数错误，请联系客服',
          duration: 3000
        });
        return;
      }
      
      console.log('调起微信支付，参数:', payData);
      console.log('当前平台:', sheep.$platform.name);
      
      // 检查是否在微信小程序环境
      if (sheep.$platform.name !== 'WechatMiniProgram') {
        console.error('当前不在微信小程序环境，无法调起微信支付');
        uni.showModal({
          title: '提示',
          content: '请在微信小程序中打开使用微信支付功能',
          showCancel: false
        });
        return;
      }
      
      // 检查 uni.requestPayment 方法是否存在
      if (typeof uni.requestPayment !== 'function') {
        console.error('uni.requestPayment 方法不存在'); 
        uni.showModal({
          title: '提示',
          content: '当前环境不支持微信支付，请在微信小程序中使用',
          showCancel: false
        });
        return;
      }
      
      // 注意：微信小程序支付不需要 provider 参数
      // uni.requestPayment 的参数直接传递支付参数即可
      uni.requestPayment({
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: payData.signType,
        paySign: payData.paySign,
        success: (res) => {
          console.log('微信支付成功', res);
          sheep.$store("user").getInfo();
          uni.showToast({icon: 'none', title: '支付成功'});
          setTimeout(() => {
            uni.navigateTo({url: '/pages/xk-movie/my-ticket'});
          }, 1500);
        },
        fail: (err) => {
          console.error('微信支付失败:', err);
          console.error('失败详情:', JSON.stringify(err));
          
          // 用户取消支付
          if (err.errMsg && err.errMsg.includes('cancel')) {
            uni.showToast({icon: 'none', title: '已取消支付'});
          } else {
            uni.showToast({icon: 'none', title: err.errMsg || '支付失败，请重试'});
          }
        }
      });
    } else {
      console.error('支付接口返回错误:', res);
      uni.showToast({icon: 'none', title: res.msg || '支付失败'});
    }
  } catch (error) {
    console.error('微信支付异常:', error);
    uni.showToast({icon: 'error', title: error.message || '支付接口调用失败'});
  }
}

function goBack() {
  uni.navigateBack({
    delta: 1,
  });
}
</script>

<style lang="scss" scoped>
page {
  background-color: #f4f5f7;
}

.amount {
  text-align: center;
  padding-top: 80rpx;
  color: #fe602b;
  font-size: 72rpx;
  font-weight: 550;

  text {
    font-size: 36rpx;
  }
}

.pay-tips {
  text-align: center;
  color: #636775;
  font-size: 28rpx;
  margin-top: 6rpx;
}

.pay-info-item {
  margin: 70rpx 32rpx 0rpx 32rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx 32rpx;

  .film-title {
    color: #2d3039;
    font-size: 36rpx;
    font-weight: 550;
    padding-bottom: 8rpx;
  }

  .film-text {
    margin-top: 12rpx;
    color: #636775;
    font-size: 28rpx;
  }
}

.pay-item {
  margin: 20rpx 25rpx 0rpx 25rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 26rpx 32rpx;
  display: flex;
  align-items: center;

  .item-left {
    display: flex;
    align-items: center;

    image {
      width: 48rpx;
      height: 48rpx;
    }

    text {
      color: #2d3039;
      font-size: 28rpx;
      margin-left: 20rpx;
    }
  }

  .pay-check {
    margin-left: auto;
    width: 36rpx;
    height: 36rpx;
  }
}

.pay-btns {
  position: fixed;
  bottom: 50rpx;
  left: 32rpx;
  right: 32rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  background-color: #fe602b;
  border-radius: 50rpx;
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 550;
}

.scroll-box {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  margin-top: 40rpx;
}

.index-nav-scroll {
  width: 100%;
}

/* 公共样式 */
.index-nav-view {
  display: inline-block;
  margin: 0rpx 22rpx;
  width: 70%;
  height: 200rpx;
  box-sizing: border-box;
  border-radius: 20rpx;
  padding: 10rpx;
}

.index {
  height: 100%;
  border-radius: 20rpx;
  box-sizing: border-box;
  font-size: 32rpx;
  padding: 10rpx;
  font-weight: 700;
  position: relative;
}

.indexradio {
  position: absolute;
  right: 0rpx;
  bottom: 10rpx;
}

/* 特定样式 */
.index-nav-view1 {
  background: linear-gradient(to right, #ffc39e, #ff8273);
}

.index1 {
  background: linear-gradient(to right, #ffdcbd, #ff9f99);
  color: #fd9744;
}

.index-nav-view2 {
  background: linear-gradient(to right, #454756, #333243);
}

.index2 {
  background: linear-gradient(to right, #4a4b56, #373541);
  border: #c8b17c solid 2rpx;
  color: #c8b17c;
}

.index-nav-view3 {
  background: linear-gradient(to right, #c181f0, #974eeb);
}

.index3 {
  background: linear-gradient(to right, #deb6fd, #8338ee);
  color: #8324b7;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 200rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-button,
.nav-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #000;
}
</style>
